package com.example.demo.listener;

import com.mybatisflex.annotation.SetListener;

/**
 * 账户持久化处理onSet之字段加密监听器
 *
 * @author raos
 * @date 2023-07-06 21:06
 */
public class AccountEncryptListener implements SetListener {

    @Override
    public int order() {
        return 1;
    }

    @Override
    public Object onSet(Object entity, String property, Object value) {
        if (isUserName(property)) {
            if (value != null) {
                return "".equals(value.toString()) ? "" : toUnicode2(value.toString());
            }
            return null;
        }

        if (isPassword(property)) {
            return "解密：" + value;
        }

        // 别忘记返回其他属性的值！！！
        return value;
    }

    public boolean isUserName(String property) {
        return "userName".equals(property);
    }

    /*** 将字符串 转为 Unicode 编码串-方式1*/
    public String toUnicode(String str) {
        StringBuilder unicode = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            unicode.append("\\u").append(Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /*** 将字符串 转为 Unicode 编码串-方式2*/
    public String toUnicode2(String str) {
        StringBuilder unicodeStr = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int codePoint = str.codePointAt(i); // 将字符串中的字符转为 Unicode 编码符数值
            unicodeStr.append(String.format("\\u%04x", codePoint));
        }
        return unicodeStr.toString();
    }

    public boolean isPassword(String property) {
        return "password".equals(property);
    }

}